package com.one.service.impl;

import com.one.bean.CollectFootpoint;
import com.one.constant.DBStatusConstant;
import com.one.constant.RedisPrefixConstant;
import com.one.constant.RequestReturnConstant;
import com.one.constant.SystemConstant;
import com.one.mapper.CollectFootpointMapper;
import com.one.service.CollectFootpointService;
import com.one.util.PageUtil;
import com.one.util.RedisUtils;
import com.one.util.RequestReturn;
import com.one.util.RequestReturnFactory;
import com.one.vo.CollectFootpointVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @ClassName: CollectFootpointServiceImpl
 * @Auther: yph
 * @Date: 2022/1/19 14:32
 * @Description: 用户收藏足迹业务层实现类
 */
@Slf4j
@Service
public class CollectFootpointServiceImpl implements CollectFootpointService {

    @Autowired(required = false)
    private CollectFootpointMapper collectFootpointMapper;

    @Autowired(required = false)
    private RedisUtils redisUtils;

    @Override
    public RequestReturn<PageUtil<List<CollectFootpointVo>>> queryFootpointByUserId(Integer userId, Integer pageNo, Integer pageSize) {
        PageUtil<List<CollectFootpointVo>> pageUtil = new PageUtil<>();
        // 设置起始页
        if (pageNo == null || pageNo < 1) {
            pageNo = SystemConstant.PAGE_NUM;
        }
        // 设置每页数据
        if (pageSize == null || pageSize < 1) {
            pageSize = SystemConstant.PAGE_SIZE;
        }
        //获取历史记录
        List<CollectFootpointVo> footpointVos = collectFootpointMapper.queryFootpointByUserId(userId, pageNo, pageSize);
        // 查询最近30天的浏览历史记录数量
        Long totalRecord = collectFootpointMapper.queryFootpointCountByUserId(userId);
        pageUtil.setPageNum(pageNo)
                .setPageSize(pageSize)
                .setData(footpointVos)
                .setTotalRecords(totalRecord)
                .setTotalPages(totalRecord / pageSize + (totalRecord % pageSize) == 0 ? 0 : 1);
        return RequestReturnFactory.success(pageUtil);
    }

    @Override
    public RequestReturn<String> collectProductToRedis(Integer userId, Integer productId) {
        String key = RedisPrefixConstant.USER_COLLECT_PREFIX + userId + ":" + productId;
        String keyStatus = key + "STATUS";
        if (!redisUtils.hasKey(keyStatus)){
            redisUtils.set(keyStatus, 0, 3);
            log.info("设置收藏过期监听键:【{}】 ,有效时间为：[{}]",keyStatus,redisUtils.getExpire(keyStatus));
        }
//        redisUtils.se
        // 频繁操作提醒
        if (!redisUtils.checkFreq(keyStatus, 3, 2)) {
            return RequestReturnFactory.success("操作频繁，请稍后再试！");
        }
        // 判断redis中是否存在相同的记录，有就取消
        if (redisUtils.hasKey(key)) {
            redisUtils.del(key);
//            redisUtils.del(keyStatus);
            return RequestReturnFactory.success("取消收藏！");
        } else {
            CollectFootpoint collect = new CollectFootpoint();
            collect.setProductId(productId)
                    .setUserId(userId)
                    .setCreateDate(new Date())
                    .setUpdateDate(new Date())
                    .setStatus(0)
                    .setType(DBStatusConstant.USER_COLLECT);
            redisUtils.set(key, collect);
            return RequestReturnFactory.success("收藏成功！");
        }
    }

    @Override
    public RequestReturn<String> collectProductsToRedis(Integer userId, List<Integer> productIds) {
        // 循环添加
        for (Integer productId : productIds) {
            String key = RedisPrefixConstant.USER_COLLECT_PREFIX + userId + ":" + productId;
            // 判断redis中是否存在相同的记录，有就不添加，没有就添加到redis以及数据库
            if (!redisUtils.hasKey(key)) {
                CollectFootpoint collect = new CollectFootpoint();
                collect.setProductId(productId)
                        .setUserId(userId)
                        .setCreateDate(new Date())
                        .setUpdateDate(new Date())
                        .setStatus(0)
                        .setType(DBStatusConstant.USER_COLLECT);
                redisUtils.set(key, collect);
                // 同步到数据库
                collectProductToMysql(collect);
            }
        }
//        return RequestReturnFactory.success("收藏成功！");

//        try {
//            productIds.forEach(productId -> collectProductToRedis(userId, productId));
//        } catch (Exception exception) {
//            log.error("=== 添加到收藏夹失败！原因：[{}]", exception.getMessage());
////            exception.printStackTrace();
//            return RequestReturnFactory.fail(RequestReturnConstant.MOVE_TO_COLLECT_ERROR_CODE, "移入收藏夹失败！");
//        }
        return RequestReturnFactory.success("移入收藏夹成功！");
    }

    @Override
    public boolean collectProductToMysql(CollectFootpoint collectFootpoint) {
        // 判断数据库中是否有值
        CollectFootpoint collect = collectFootpointMapper.queryBuUserIdAndProductId(collectFootpoint.getUserId(), collectFootpoint.getProductId());
        if (collect == null) {
            //数据库中没有数据就直接添加
            return collectFootpointMapper.insert(collectFootpoint) > 0;
        } else {
            // 如果数据库中能够查询出来，证明收藏状态是已删除改变  需要改变收藏状态
            return collectFootpointMapper.updateById(collect.setStatus(0).setUpdateDate(new Date())) > 0;
        }
    }

    @Override
    public boolean deleteCollectProduct(String userId, String productId) {
        CollectFootpoint collect = collectFootpointMapper.queryBuUserIdAndProductId(userId, productId);
        if (collect != null) {
            // 如果数据库中能够查询出来，需要删除该数据
            return collectFootpointMapper.updateById(collect.setStatus(1).setUpdateDate(new Date())) > 0;
        }
        return true;
    }

    @Override
    public RequestReturn<List<CollectFootpointVo>> queryCollectProduct(Integer userId) {
//        从redis中读取没有收藏id
//        Set<String> keys = redisUtils.keys(RedisPrefixConstant.USER_COLLECT_PREFIX + userId);
//        System.out.println("================");
//        List<Integer> productIds=new ArrayList<>();
//        List<CollectFootpointVo> collectFootpointVos=new ArrayList<>();
//        keys.forEach(
//                key->{
//                    String productId = key.replaceAll(RedisPrefixConstant.USER_COLLECT_PREFIX + userId + ":" ,"");
//                    productIds.add(Integer.valueOf(productId));
//                    CollectFootpointVo collectFootpointVo=new CollectFootpointVo();
//                    collectFootpointVo.setType(DBStatusConstant.USER_COLLECT);
//                }
//        );
//        if(!productIds.isEmpty()){
//             = collectFootpointMapper.queryProductNameByProductId(productIds);
//
//        }
//        return RequestReturnFactory.success(null);
        return RequestReturnFactory.success(collectFootpointMapper.queryCollectByUserId(userId));
    }

    @Override
    public RequestReturn<String> clearUserCollect(Integer userId) {
        // 清空数据库，
        int i = 0;
        try {
            i = collectFootpointMapper.clearUserCollect(userId);
        } catch (Exception exception) {
            log.error("==== 清空用户收藏失败,原因：[{}] ====", exception.getMessage());
            return RequestReturnFactory.fail(RequestReturnConstant.CLEAR_USER_COLLECT_ERROR_CODE, RequestReturnConstant.CLEAR_USER_COLLECT_ERROR_MSG);
        }
        if (i == 0)
            return RequestReturnFactory.success("当前用户没有收藏商品！");
        // 清空redis，
        Set<String> keys = redisUtils.keys(RedisPrefixConstant.USER_COLLECT_PREFIX + userId + ":");
        // 删除匹配的数据
        keys.forEach(redisUtils::del);

        return RequestReturnFactory.success("清空收藏夹成功！");
    }

    @Override
    public RequestReturn<String> clearUserFootPoint(Integer userId) {
        try {
            collectFootpointMapper.clearUserFootPoint(userId);
        } catch (Exception exception) {
            log.error("==== 清空用户收藏失败,原因：[{}] ====", exception.getMessage());
            return RequestReturnFactory.fail(RequestReturnConstant.CLEAR_USER_FOOTPOINT_ERROR_CODE, RequestReturnConstant.CLEAR_USER_FOOTPOINT_ERROR_MSG);
        }
        return RequestReturnFactory.success("清空用户足迹成功！");
    }
}
